$(function() {
	$('#my_tree_grid').jqGrid({
		url : "findListJson.do",
		height : "400px",
		autowidth:true,
		datatype: 'json',
		mtype: 'POST',
		ExpandColClick: true,
		ExpandColumn : "name",
		treeGrid: true,
		treeGridModel : "adjacency",
		treeReader : {
			"parent_id_field" : "parentId",
			"leaf_field" : "isLeafName",
			"level_field":"level",
		},
		colModel : [ {
			"name" : "id",
			"key" : true,
			"hidden" : true
		}, 
		 {
			"name" : "name",
			"label" : "区域名称",
		}, {
			"name" : "code",
			"label" : "地区编码",
		}, {
			"name" : "parentCode",
			"label" : "父级编码",
		} , {
			"name" : "parentName",
			"label" : "父级名称",
		} 
		],
		pager: "false",  
		gridComplete: function(){
			var gridtree = $("#my_tree_grid");
			var row = gridtree.jqGrid("getLocalRow","0");
			gridtree.jqGrid('expandRow', row);
		},
		onSelectRow: function (rowid, status) {
			editArea(1);
		},
	}); 
	
	initTree();
	
	$(".btn-add").click(function(){
		addArea();
	});
	$(".btn-update").click(function(){
		editArea();
	});
	$(".btn-delete").click(function(){
		doDel();
	});
	
	validata();
});

function changeEditShow(showview){
	if(showview){
		$(".changeRead").attr("readonly","readonly");
		$(".ifshow").hide();
	}else{
		$(".changeRead").removeAttr("readonly");
		$(".ifshow").show();
	}
}
function addArea(){
	clearform('myform');
	selectTreeNode('0'); 
	$('#openinfo').show();
}

function editArea(showview){
	clearform('myform');
	var treegrid = $("#my_tree_grid");
	var rowId=treegrid.jqGrid('getGridParam','selrow');
	if(rowId == 0){
		$('#openinfo').hide();
		return;
	}
	if(rowId == null){
		RM.msg("请选择要编辑的地区！");
		return;
	}
	
	var nodes = [];
	nodes[0] = treegrid.jqGrid('getRowData',rowId);
	if(nodes.length > 1){
		RM.msg("请只选择一个地区编辑！");
		return;
	}
	var rowsData = nodes[0];
	selectTreeNode(rowsData.parentId); 
	$('#form_id').val(rowsData.id);
    $('#form_name').val(rowsData.name);
    $('#form_code').val(rowsData.code);
	$('#openinfo').show();
}
function doDel(){
	var treegrid = $("#my_tree_grid");
	var rowId=treegrid.jqGrid('getGridParam','selrow');
	if(rowId == 0){
		return;
	}
	if(rowId == null){
		RM.msg("请选择要删除的地区！");
		return;
	}
	var nodes = [];
	nodes[0] = treegrid.jqGrid('getRowData',rowId);
	if(nodes.length > 1){
		RM.msg("请只选择一个要删除的地区！");
		return;
	}
	RM.confirm("确认删除所选的记录吗?", function (){
		var rowsData = nodes[0];
		if(!postFlag){
			var callback= function(){
				var grid = $('#my_tree_grid');
				grid.jqGrid('setGridParam',{datatype:'json', nodeid : null}).trigger("reloadGrid"); 
				initTree();
			}
			sendMyAjax("del.do","id="+rowsData.id,callback);
			$('#openinfo').hide();
		}
		RM.close();
	});
	
}
function doSave(){
	$("#myform").submit();
}


function selectTreeNode(id){
	var zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo"); 
	var node = zTree_Menu.getNodeByParam("id",id );  
    zTree_Menu.selectNode(node,true);//指定选中ID的节点  
    zTree_Menu.expandNode(node, true, false);//指定选中ID节点展开
    
    $("#form_parentId").val(id);
    $("#form_parentId2").val(node.parentId);
    $("#areaName").val(node.name);
}

var setting = {
    view: {
    	selectedMulti: false,
    	dblClickExpand: false
    },
    check: {
        enable: false
    },
    data : {  
        key : {  
            name : "name"  
        },  
        simpleData : {  
            enable : true,  
            idKey : "id",  
            pIdKey : "parentId",  
            rootPId : 0  
        }  
    },   
    edit: {
        enable: false
    },
    callback: {
    	onClick: zTreeOnClick
	}
};

function initTree(){
	$.post("../area/findAllJson.do",{},function (data){
 		$.fn.zTree.init($("#treeDemo"), setting, data); 
	},"json");
}
function zTreeOnClick(event, treeId, treeNode) {
    if (treeNode) {
         $("#form_parentId").val(treeNode.id);
         $("#form_parentId2").val(treeNode.parentId);
         $("#areaName").val(treeNode.name);
    }
    hideMenu();
}
function showMenu() {
	var cityObj = $("#areaName");
	var cityOffset = $("#areaName").offset();
	$("#menuContent").css({left:0, top:"30px",width:$("#menuContent").closest(".input-group").width()}).slideDown("fast");
	$("body").bind("mousedown", onBodyDown);
}
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
		hideMenu();
	}
}

var postFlag = false;

function clearform(formid){
	$('#'+formid)[0].reset();
    $("#"+formid+" :input").not(":button, :submit, :reset, .clear_save ").val("").removeAttr("checked").remove("selected"); 
    $("#"+formid+" .error").html("");
}

function sendMyAjax(url,data,callback){
	postFlag = true;
	$.ajax({
		   type: "POST",
		   url:url,
		   data:data, 
		   success: function(msg){
			   if(msg.code != '0'){
				  RM.alert(msg.message);
			   }else{
				 callback(); 
			   }
			   postFlag = false;
		   } ,
		   error: function(error){
			   RM.alert(error);
			   postFlag = false;
		   }
	});
}
function validata(){
	$("#myform").validate({
		submitHandler: function() {
			if(!postFlag){
				var callback= function(){
					var grid = $('#my_tree_grid');
					grid.jqGrid('setGridParam',{datatype:'json', nodeid : null}).trigger("reloadGrid"); 
					
					initTree();
					$('#openinfo').hide();
					RM.msg("操作成功！");
				};
				sendMyAjax("save.do",$('#myform').serialize(),callback);
			}
		}
	});
}